// 包含gre
export const isDark = () => {
  return ['dark', 'gre'].includes(document.body.parentElement.getAttribute('data-type-color'));
};

export const isTRSingle = () => {
  return true;
  if (TERMINAL_ENV === 'SUB' && process.env.NODE_ENV === 'development') return true;
  return false;
};

export const isMain = () => {
  return window.__POWERED_BY_QIANKUN__ !== undefined;
};

//防抖
export const Debounce = (func, wait) => {
  let timeout;
  return function () {
    /* eslint-disable */
    let context = this;
    /* eslint-enable */
    let args = arguments;

    if (timeout) clearTimeout(timeout);

    let callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);

    if (callNow) func.apply(context, args);
  };
};

export const downloadHandle = (blob, fileName = 'abcdefg.zip') => {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    //此写法兼容可火狐浏览器
    document.body.appendChild(link);
    var evt = document.createEvent('MouseEvents');
    evt.initEvent('click', false, false);
    link.dispatchEvent(evt);
    document.body.removeChild(link);
  }
};

export function replaceGetParam(url = '', params = {}) {
  let keys = Object.keys(params);
  let values = Object.values(params);
  let resultUrl = url;
  keys.forEach((item, index) => {
    resultUrl = resultUrl.replace(
      '{' + item + '}',
      Array.isArray(values[index]) ? values[index].join('') : values[index],
    );
  });
  return resultUrl;
}

export function replaceGetMethodParam(url = '', params = {}) {
  if (!url || typeof url !== 'string') return url;

  let resultUrl = url.replace(/\{(\w+)\}/g, (_, key) => {
    const value = params[key];
    return value !== undefined ? encodeURIComponent(value) : `{${key}}`;
  });

  const queryParams = Object.entries(params)
    .filter(([key, value]) => !url.includes(`{${key}}`) && typeof value !== 'object')
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');

  if (queryParams) {
    resultUrl += (resultUrl.includes('?') ? '&' : '?') + queryParams;
  }

  return resultUrl;
}

/**
 * @param {*} content `<div></div>` 或者ref.cureent.innerHTML
 * @param {*} options
 * @returns
 */
export async function printContent(content, options = {}) {
  return new Promise((resolve) => {
    const config = {
      zoom: 1,
      direction: 'portrait', //横向landscape、竖向portrait
      title: '打印页面',
      pageType: 'A4',
      ...options,
    };
    const headDom = document.getElementsByTagName('head')[0];
    const iframe = document.createElement('iframe');
    iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
    const f = document.body.appendChild(iframe);
    const w = f.contentWindow || f.contentDocument;
    const doc = f.contentDocument || f.contentWindow.document;
    const pritDiv = document.createElement('div');
    pritDiv.setAttribute('style', `zoom: ${config.zoom};transform:rotate(0deg);overflow:hidden;`);
    pritDiv.innerHTML = content;
    doc.body.appendChild(pritDiv);
    const head = doc.getElementsByTagName('head')[0];
    head.innerHTML =
      headDom.innerHTML +
      `<style type='text/css'>@page {size:${config.pageType} ${config.direction};margin:0}</style>`;
    head.getElementsByTagName('title')[0].innerHTML = '打印页面';
    doc.close();
    // w.focus();
    setTimeout(() => {
      w.print();
      w.close();
      document.body.removeChild(iframe);
      resolve();
    }, 1000);
  });
}
